import { $t } from '@/i18n'
import { CHECK_ACCOUNT_EXISTS } from '@const'
import API from '@/http'

function checkObject(obj) {
  if (!('value' in obj) || !(`canUse` in obj) || !(`error` in obj))
    throw new Error('[check-account]] Object is not valid.')
  return !!obj.value
}

export async function checkAccountExist(obj, type) {
  if (!checkObject(obj)) {
    console.error('[check-account] Object is not valid.')
    return
  }
  try {
    const response = await API.Auth.exists({ data: { type, name: obj.value } })
    if (!response) {
      obj.error =
        type === CHECK_ACCOUNT_EXISTS.ACCOUNT
          ? $t('yup.string.exists.account')
          : type === CHECK_ACCOUNT_EXISTS.USERNAME
          ? $t('yup.string.exists.username')
          : $t('yup.string.exists.email')
      console.log(obj.error)
    }
    obj.canUse = response
  } catch (e) {
    console.error(`[check-account] ${e}`)
  }
}
